import { asyncRoutes, constantRoutes, errorRoutes } from '@/router'
import { getInfo } from '@/api/user'
import Layout from '@/layout'
import { Message } from "element-ui"

// debugger
/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * 这里是demo使用的是以前项目的后台数据，这里强制修改了一下
//  *  @param routes
 */
export function generaMenu(routes, data, parent) {
  data.forEach(item => {
    let menu
    if (parent === '#') {
      menu = {
        path: item.path,
        component: Layout,
        children: [],
        redirect: `${item.path}`,
        meta: { title: item.name, icon: 'icon-' + item.icon}
      }
    } else {
      menu = {
        path: item.path,
        component: loadView(parent, item.path),
        name: item.name,
        meta: { title: item.name }
      }
    }
    if (item.linkList) {
      generaMenu(menu.children, item.linkList, item.path)
    }
    routes.push(menu)
  })
}

export const loadView = (parent, path) => { // 路由懒加载
  return (resolve) => require([`@/views${parent}${path}`], resolve)
  // return () => import(`@/views${parent}/${path}/index`)
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes).concat(errorRoutes)
  }

}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const loadMenuData = []
      // 先查询后台并返回左侧菜单数据并把数据添加到路由
      getInfo().then(response => {
        if (response.code !== 200) {
          Message({
            message: "菜单数据加载异常",
            type: 0,
            duration: 2 * 1000
          });
        } else {
          let datas = response.data
          Object.assign(loadMenuData, datas)
          let routes = []
          generaMenu(routes, loadMenuData, "#")
          let accessedRoutes = routes || []
          commit('SET_ROUTES', accessedRoutes)
          console.log(accessedRoutes)
          resolve(accessedRoutes)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


